package city.spring.modules.personnel.controller;

import city.spring.modules.personnel.entity.EmployeeNoticeEntity;
import city.spring.modules.personnel.service.EmployeeNoticeService;
import city.spring.modules.system.entity.OrganizationEntity;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.OrganizationService;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller：通知公告
 *
 * @author Panxm
 * @date 2020-04-10 11:12:16
 */
@RestController
@RequestMapping("/employee_notice")
public class EmployeeNoticeController extends ApiController {
    private final EmployeeNoticeService employeeNoticeService;
    private final UserService userService;
    private final OrganizationService organizationService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<EmployeeNoticeEntity, ?>> entityOrderFields;

    public EmployeeNoticeController(EmployeeNoticeService employeeNoticeService, UserService userService, OrganizationService organizationService) {
        this.employeeNoticeService = employeeNoticeService;
        this.userService = userService;
        this.organizationService = organizationService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(EmployeeNoticeEntity::getId);
        entityOrderFields.add(EmployeeNoticeEntity::getNoticeNum);
        entityOrderFields.add(EmployeeNoticeEntity::getTitle);
        entityOrderFields.add(EmployeeNoticeEntity::getPublisher);
        entityOrderFields.add(EmployeeNoticeEntity::getDept);
        entityOrderFields.add(EmployeeNoticeEntity::getCreatTime);
        entityOrderFields.add(EmployeeNoticeEntity::getContent);
        entityOrderFields.add(EmployeeNoticeEntity::getAttachment);
    }

    /**
     * 获取全部的 <strong>通知公告</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, EmployeeNoticeEntity entity) {
        LambdaQueryChainWrapper<EmployeeNoticeEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>通知公告</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, EmployeeNoticeEntity entity) {
        LambdaQueryChainWrapper<EmployeeNoticeEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<EmployeeNoticeEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        // 发布人id显示为名字,部门id显示名字
        for (EmployeeNoticeEntity record : page.getRecords()) {
            try {
                UserEntity userEntity = userService.getById(record.getPublisher());
                record.setPublisherName(userEntity.getUsername());

            } catch (Exception ignore) {
                record.setPublisher(null);
                record.setPublisherName("< 找不到员工 >");

            }
            try {
                OrganizationEntity organizationEntity = organizationService.getById(record.getDept());
                if (organizationEntity != null) {
                    record.setDeptName(organizationEntity.getTitle());
                }
            } catch (Exception ignore) {
                record.setDept(null);
                record.setDeptName("找不到部门");
            }
        }
        return success(page);
    }

    /**
     * 获取一个 <strong>通知公告</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(employeeNoticeService.getById(id));
    }

    /**
     * 添加一个 <strong>通知公告</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody EmployeeNoticeEntity entity, @NonNull Principal user) {
        employeeNoticeService.saveEmployeeNotice(entity, user);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>通知公告</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody EmployeeNoticeEntity entity) {
        entity.setId(id);
        employeeNoticeService.updateEmployeeNotice(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>通知公告</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        employeeNoticeService.deleteEmployeeNotice(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>通知公告</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        employeeNoticeService.deleteEmployeeNotice(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<EmployeeNoticeEntity> buildLambdaQuery(EmployeeNoticeEntity entity) {
        LambdaQueryChainWrapper<EmployeeNoticeEntity> lambdaQuery = employeeNoticeService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), EmployeeNoticeEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getNoticeNum()), EmployeeNoticeEntity::getNoticeNum, entity.getNoticeNum());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitle()), EmployeeNoticeEntity::getTitle, entity.getTitle());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPublisher()), EmployeeNoticeEntity::getPublisher, entity.getPublisher());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDept()), EmployeeNoticeEntity::getDept, entity.getDept());
        lambdaQuery.like(entity.getCreatTime() != null, EmployeeNoticeEntity::getCreatTime, entity.getCreatTime());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getContent()), EmployeeNoticeEntity::getContent, entity.getContent());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAttachment()), EmployeeNoticeEntity::getAttachment, entity.getAttachment());
        return lambdaQuery;
    }

}
